const rateLimit = require('express-rate-limit');
const config = require('../config/config');
const { logger } = require('../utils/logger');

const rateLimiter = rateLimit({
  windowMs: config.rateLimit.windowMs,
  max: config.rateLimit.max,
  message: {
    error: '请求过于频繁，请稍后重试',
    retryAfter: Math.ceil(config.rateLimit.windowMs / 1000)
  },
  standardHeaders: true,
  legacyHeaders: false,
  handler: (req, res) => {
    logger.warn(`IP ${req.ip} 触发频率限制`);
    res.status(429).json({
      success: false,
      error: '请求过于频繁，请稍后重试',
      retryAfter: Math.ceil(config.rateLimit.windowMs / 1000)
    });
  }
});

module.exports = rateLimiter;
